package com.base.util;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.base.common.SysParam;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;


public class JedisPoolUtils {

	private static final Log logger = LogFactory.getLog(JedisPoolUtils.class);

	private static JedisSentinelPool jedisPool;

	static {
		try {
			init();
		} catch (Exception e) {
			logger.error("jedis init error ", e);
		}
	}

	private static void init() {
		int maxActive = Integer.parseInt(SysParam
				.getSysParam("redis.pool.maxActive"));
		int maxIdle = Integer.parseInt(SysParam
				.getSysParam("redis.pool.maxIdle"));
		int maxWait = Integer.parseInt(SysParam
				.getSysParam("redis.pool.maxWait"));
		String sentinelip = SysParam.getSysParam("redis.sentinel.server.ip");
		String sentinelport = SysParam
				.getSysParam("redis.sentinel.server.port");
		String mastername = SysParam.getSysParam("master.name");
		String sentinelpwd = SysParam.getSysParam("redis.sentinel.server.password");
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMaxIdle(maxIdle);
		config.setMaxTotal(maxActive);
		config.setMaxWaitMillis(maxWait);
		Set<String> sentinel = new HashSet<String>();
		sentinel.add(new HostAndPort(sentinelip, Integer.parseInt(sentinelport))
				.toString());
		jedisPool = new JedisSentinelPool(mastername, sentinel, config,sentinelpwd);
	}

	public static JedisSentinelPool getJedisPool() {
		return jedisPool;
	}
	public static Jedis getJedis(){
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
		} catch (Exception e) {
			logger.error(e);
			init();
			jedis = jedisPool.getResource();
		}
		return jedis;
	}
	public static void returnResource(Jedis jedis){
		jedisPool.returnResourceObject(jedis);
	}
}
